package com.chant.startFarming.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chant.startFarming.dto.Result;
import com.chant.startFarming.entity.Pens;
import com.chant.startFarming.service.IPensService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

/**
 * <p>
 * 圈舍表，存储圈舍的基本信息和状态 前端控制器
 * </p>
 *
 * @author chant
 * @since 2025-03-31
 */
@RestController
@RequestMapping("/pens")
public class PensController {

    @Autowired
    private IPensService pensService;

    // 查询所有圈舍
    @GetMapping
    public Result getAllPens(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<Pens> pensList = pensService.list();
        PageInfo<Pens> pageInfo = new PageInfo<>(pensList);

        return Result.ok(pensList, pageInfo.getTotal());
    }

    // 根据ID查询圈舍
    @GetMapping("/{id}")
    public Result getPenById(@PathVariable Integer id) {
        Pens pens = pensService.getById(id);
        if( null != pens ) {
            return Result.ok(pens);
        } else {
            return Result.fail("pens not found");
        }
    }

    // 添加圈舍
    @PostMapping
    public Result addPen(@RequestBody Pens pen) {
        boolean saved = pensService.save(pen);
        if (saved) {
            return Result.ok();
        } else {
            return Result.fail("Failed to add pen");
        }
    }

    // 更新圈舍
    @PutMapping
    public Result updatePen(@RequestBody Pens pen) {
        boolean updated = pensService.updateById(pen);
        if (updated) {
            return Result.ok();
        } else {
            return Result.fail("Failed to update pen");
        }
    }

    // 删除圈舍
    @DeleteMapping("/{id}")
    public Result deletePen(@PathVariable Integer id) {
        boolean deleted = pensService.removeById(id);
        if (deleted) {
            return Result.ok();
        } else {
            return Result.fail("Failed to delete pen");
        }
    }

    // 根据名称模糊查找和根据状态查找
    @GetMapping("/search")
    public Result searchPens(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer pensStatus,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 开始分页
        PageHelper.startPage(pageNum, pageSize);

        List<Pens> pens = pensService.searchPens(name, pensStatus);
        PageInfo<Pens> pageInfo = new PageInfo<>(pens);

        return Result.ok(pens, pageInfo.getTotal());
    }

}
